/**
 * 数据存取层
 *
 * @author bian
 * @createDate 2016.9.8
 */
const models = require("../models/index").models;
const Data = models.Data;

var DataAdaptor = module.exports = (function(){
    var getState = function (equipment,type) {
        return Data.findOne({
            where:{
                equipment : equipment,
                type : type
            }
        });
    };

    var getData = function(equipment,type,limit,time,duration){
        return Data.findAll({
            where:{
                type : type,
                equipment: equipment,
                createdAt : {
                    $gt : new Date(new Date(parseInt(time)) - duration * 1000)
                }
            },
            limit : limit,
            order : [["createdAt","DESC"]]
        });
    };

    var setState = function(equipment,type,value){
        return Data.update({
            value : value
        },{
            where : {
                equipment : equipment,
                type : type
            }
        });
    };

    var setPlan = function(equipment,value){
        return Data.update({
            value : value
        },{
            where:{
                equipment : equipment,
                type : "plan"
            }
        });
    };

    var getPlans = function(){
        return Data.findAll({
            where:{
                type : "plan"
            }
        });
    };

    return {
        getState,
        getData,
        setState,
        setPlan,
        getPlans
    }
}());

